package com.yzxb.messystem.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.yzxb.messystem.util.ResponseResult;

@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    
    // 处理资源不存在异常
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseResult handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
        return ResponseResult.error(
                HttpStatus.NOT_FOUND.value(),
                ex.getMessage()
        );
    }
    
    // 处理业务逻辑异常
    @ExceptionHandler(BusinessException.class)
    public ResponseResult handleBusinessException(BusinessException ex, WebRequest request) {
        return ResponseResult.error(
                HttpStatus.BAD_REQUEST.value(),
                ex.getMessage()
        );
    }
    
    // 处理数据验证异常
    @ExceptionHandler(ValidationException.class)
    public ResponseResult handleValidationException(ValidationException ex, WebRequest request) {
        ResponseResult result = ResponseResult.error(
                HttpStatus.UNPROCESSABLE_ENTITY.value(),
                "数据验证失败",
                ex.getFieldErrors()
        );
        return result;
    }
    
    // 处理所有其他异常
    @ExceptionHandler(Exception.class)
    public ResponseResult handleGlobalException(Exception ex, WebRequest request) {
        // 记录异常日志
        ex.printStackTrace();
        
        return ResponseResult.error(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "系统内部错误，请联系管理员"
        ).addExtra("exception", ex.getClass().getSimpleName());
    }
    

}